4fcea065221969b03de850011c0eb4ce6a9828e8
[nextcloud-desktop.git] /
1 //
2 //  ShareTableViewDataSource.swift
3 //  FileProviderUIExt
4 //
5 //  Created by Claudio Cambra on 27/2/24.
6 //
7
8 import AppKit
9 import FileProvider
10 import NextcloudKit
11 import NextcloudFileProviderKit
12 import NextcloudCapabilitiesKit
13 import OSLog
14
15 class ShareTableViewDataSource: NSObject, NSTableViewDataSource, NSTableViewDelegate {
16     private let shareItemViewIdentifier = NSUserInterfaceItemIdentifier("ShareTableItemView")
17     private let shareItemViewNib = NSNib(nibNamed: "ShareTableItemView", bundle: nil)
18     private let reattemptInterval: TimeInterval = 3.0
19
20     let kit = NextcloudKit.shared
21
22     var uiDelegate: ShareViewDataSourceUIDelegate?
23     var sharesTableView: NSTableView? {
24         didSet {
25             sharesTableView?.register(shareItemViewNib, forIdentifier: shareItemViewIdentifier)
26             sharesTableView?.rowHeight = 42.0  // Height of view in ShareTableItemView XIB
27             sharesTableView?.dataSource = self
28             sharesTableView?.delegate = self
29             sharesTableView?.reloadData()
30         }
31     }
32     var capabilities: Capabilities?
33     var itemMetadata: NKFile?
34
35     private(set) var itemURL: URL?
36     private(set) var itemServerRelativePath: String?
37     private(set) var shares: [NKShare] = [] {
38         didSet { Task { @MainActor in sharesTableView?.reloadData() } }
39     }
40     private(set) var account: Account? {
41         didSet {
42             guard let account = account else { return }
43             kit.appendSession(
44                 account: account.ncKitAccount,
45                 urlBase: account.serverUrl,
46                 user: account.username,
47                 userId: account.username,
48                 password: account.password,
49                 userAgent: "Nextcloud-macOS/FileProviderUIExt",
50                 nextcloudVersion: 25,
51                 groupIdentifier: ""
52             )
53         }
54     }
55
56     func loadItem(url: URL) {
57         itemServerRelativePath = nil
58         itemURL = url
59         Task {
60             await reload()
61         }
62     }
63
64     func reattempt() {
65         DispatchQueue.main.async {
66             Timer.scheduledTimer(withTimeInterval: self.reattemptInterval, repeats: false) { _ in
67                 Task { await self.reload() }
68             }
69         }
70     }
71
72     func reload() async {
73         guard let itemURL else {
74             presentError("No item URL, cannot reload data!")
75             return
76         }
77         guard let itemIdentifier = await withCheckedContinuation({
78             (continuation: CheckedContinuation<NSFileProviderItemIdentifier?, Never>) -> Void in
79             NSFileProviderManager.getIdentifierForUserVisibleFile(
80                 at: itemURL
81             ) { identifier, domainIdentifier, error in
82                 defer { continuation.resume(returning: identifier) }
83                 guard error == nil else {
84                     self.presentError("No item with identifier: \(error.debugDescription)")
85                     return
86                 }
87             }
88         }) else {
89             presentError("Could not get identifier for item, no shares can be acquired.")
90             return
91         }
92
93         do {
94             let connection = try await serviceConnection(url: itemURL, interruptionHandler: {
95                 Logger.sharesDataSource.error("Service connection interrupted")
96             })
97             guard let serverPath = await connection.itemServerPath(identifier: itemIdentifier),
98                   let credentials = await connection.credentials() as? Dictionary<String, String>,
99                   let convertedAccount = Account(dictionary: credentials),
100                   !convertedAccount.password.isEmpty
101             else {
102                 presentError("Failed to get details from File Provider Extension. Retrying.")
103                 reattempt()
104                 return
105             }
106             let serverPathString = serverPath as String
107             itemServerRelativePath = serverPathString
108             account = convertedAccount
109             await sharesTableView?.deselectAll(self)
110             capabilities = await fetchCapabilities()
111             guard capabilities != nil else { return }
112             guard capabilities?.filesSharing?.apiEnabled == true else {
113                 presentError("Server does not support shares.")
114                 return
115             }
116             guard let account else {
117                 presentError("Account data is unavailable, cannot reload data!")
118                 return
119             }
120             itemMetadata = await fetchItemMetadata(
121                 itemRelativePath: serverPathString, account: account, kit: kit
122             )
123             guard itemMetadata?.permissions.contains("R") == true else {
124                 presentError("This file cannot be shared.")
125                 return
126             }
127             shares = await fetch(
128                 itemIdentifier: itemIdentifier, itemRelativePath: serverPathString
129             )
130         } catch let error {
131             presentError("Could not reload data: \(error), will try again.")
132             reattempt()
133         }
134     }
135
136     private func fetch(
137         itemIdentifier: NSFileProviderItemIdentifier, itemRelativePath: String
138     ) async -> [NKShare] {
139         Task { @MainActor in uiDelegate?.fetchStarted() }
140         defer { Task { @MainActor in uiDelegate?.fetchFinished() } }
141
142         let rawIdentifier = itemIdentifier.rawValue
143         Logger.sharesDataSource.info("Fetching shares for item \(rawIdentifier, privacy: .public)")
144
145         guard let account else {
146             self.presentError("NextcloudKit instance or account is unavailable, cannot fetch shares!")
147             return []
148         }
149
150         let parameter = NKShareParameter(path: itemRelativePath)
151
152         return await withCheckedContinuation { continuation in
153             kit.readShares(
154                 parameters: parameter, account: account.ncKitAccount
155             ) { account, shares, data, error in
156                 let shareCount = shares?.count ?? 0
157                 Logger.sharesDataSource.info("Received \(shareCount, privacy: .public) shares")
158                 defer { continuation.resume(returning: shares ?? []) }
159                 guard error == .success else {
160                     self.presentError("Error fetching shares: \(error.errorDescription)")
161                     return
162                 }
163             }
164         }
165     }
166
167     private static func generateInternalShare(for file: NKFile) -> NKShare {
168         let internalShare = NKShare()
169         internalShare.shareType = NKShare.ShareType.internalLink.rawValue
170         internalShare.url = file.urlBase +  "/index.php/f/" + file.fileId
171         internalShare.account = file.account
172         internalShare.displaynameOwner = file.ownerDisplayName
173         internalShare.displaynameFileOwner = file.ownerDisplayName
174         internalShare.path = file.path
175         return internalShare
176     }
177
178     private func fetchCapabilities() async -> Capabilities? {
179         guard let account else {
180             self.presentError("Could not fetch capabilities as account is invalid.")
181             return nil
182         }
183
184         return await withCheckedContinuation { continuation in
185             kit.getCapabilities(account: account.ncKitAccount) { account, data, error in
186                 guard error == .success, let capabilitiesJson = data?.data else {
187                     self.presentError("Error getting server caps: \(error.errorDescription)")
188                     continuation.resume(returning: nil)
189                     return
190                 }
191                 Logger.sharesDataSource.info("Successfully retrieved server share capabilities")
192                 continuation.resume(returning: Capabilities(data: capabilitiesJson))
193             }
194         }
195     }
196
197     private func presentError(_ errorString: String) {
198         Logger.sharesDataSource.error("\(errorString, privacy: .public)")
199         Task { @MainActor in self.uiDelegate?.showError(errorString) }
200     }
201
202     // MARK: - NSTableViewDataSource protocol methods
203
204     @objc func numberOfRows(in tableView: NSTableView) -> Int {
205         shares.count
206     }
207
208     // MARK: - NSTableViewDelegate protocol methods
209
210     @objc func tableView(
211         _ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int
212     ) -> NSView? {
213         let share = shares[row]
214         guard let view = tableView.makeView(
215             withIdentifier: shareItemViewIdentifier, owner: self
216         ) as? ShareTableItemView else {
217             Logger.sharesDataSource.error("Acquired item view from table is not a share item view!")
218             return nil
219         }
220         view.share = share
221         return view
222     }
223
224     @objc func tableViewSelectionDidChange(_ notification: Notification) {
225         guard let selectedRow = sharesTableView?.selectedRow, selectedRow >= 0 else {
226             Task { @MainActor in uiDelegate?.hideOptions(self) }
227             return
228         }
229         let share = shares[selectedRow]
230         Task { @MainActor in uiDelegate?.showOptions(share: share) }
231     }
232 }